package com.xiaojimao.gr_user.interceptor;

import com.xaiojimao.gr_common.CommonEnum.BizCommonEnum;
import com.xaiojimao.gr_common.Utils.AsserUtils;
import com.xaiojimao.gr_common.Utils.JwtUtils;
import com.xaiojimao.gr_common.dto.RequestInfo;
import com.xiaojimao.gr_user.ThreadLocal.UserThread;
import com.xiaojimao.gr_user.dao.UserDao;
import com.xiaojimao.gr_user.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserInterceptor implements HandlerInterceptor {

    @Autowired
    private UserDao userDao;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        AsserUtils.isEmpty(token,"token不能为空");
        AsserUtils.isFalse(JwtUtils.isTokenValid(token), BizCommonEnum.USER_OUT_LOGIN_ERROR);
        String id = JwtUtils.getTokenInfo(token);
        User user = userDao.getById(id);
        String status = user.getStatus();
        AsserUtils.isTrue("0".equals(status),BizCommonEnum.USER_STATUS_ERROR);
        RequestInfo requestInfo = new RequestInfo();
        requestInfo.setUserId(id);
        UserThread.set(requestInfo);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        UserThread.remove();
    }

}
